// import Router from 'koa-router'
// import Redis from 'koa-redis'
// import nodeMailer from 'nodemailer'
// import User from '../dbs/models/users'
// import Passport from './utils/passport'
// import Email from '../dbs/config'
// import axios from './utils/axios'
const Router = require('koa-router')
const Redis = require('koa-redis')
const nodeMailer = require('nodemailer')
const User = require('../dbs/models/users')
const Passport = require('./utils/passport')
const Email = require('../dbs/config')
const axios = require('./utils/axios')

const mysqlp = require('../api/utils/mysql-p')


let router = new Router({prefix: '/users'})

let Store = new Redis().client

/*
  注册
*/
router.post('/signup', async (ctx) => {
  const {password, email, code} = ctx.request.body

  // let username = ''

  if (code) {
    const saveCode = await Store.hget(`nodemail:${email}`, 'code')
    const saveExpire = await Store.hget(`nodemail:${email}`, 'expire')
    if (code === saveCode) {
      if (new Date().getTime() - saveExpire > 1000 * 60 * 30) {
        ctx.body = {
          code: -1,
          msg: '验证码已过期，请重新尝试'
        }
        return false
      }
    } else {
      ctx.body = {
        code: -1,
        msg: '请填写正确的验证码'
      }
    }
  } else {
    ctx.body = {
      code: -1,
      msg: '请填写验证码'
    }
  }
  // 邮箱
  if (!email) {
    ctx.body = {
      code: -1,
      msg: '请填写邮箱'
    }
    return
  }
  // 密码
  if (!password) {
    ctx.body = {
      code: -1,
      msg: '请填写密码'
    }
    return
  }
  // 邮箱
  // let user = await User.find({email})
  let user = await mysqlp.query(`select email from user where email='${email}';`)
  console.log(user[0]);
  if (user[0]) {
    ctx.body = {
      code: -1,
      msg: '该邮箱已被注册'
    }
    return
  }
  
  // let nuser = await User.create({email, password})

  let nuser = await mysqlp.query(`INSERT INTO user
        (email,password, username)
        VALUES
        ('${email}','${password}','${email}');`)

  console.log(nuser)
  // return

  if (nuser) {
    // let {password, email} = nuser
    // console.log('email', email)
    // console.log(password)

    let res = await axios.post('/users/login', {email, password})
    // console.log('res', res)
    if (res.data && res.data.code === 0) {
      ctx.body = {
        code: 0,
        msg: '注册成功',
        user: res.data.user
      }
    } else {
      ctx.body = {
        code: -1,
        msg: 'error'
      }
    }
  } else {
    ctx.body = {
      code: -1,
      msg: '注册失败'
    }
  }
})
/*
  登录
*/
router.post('/login',async (ctx, next) => {
  // const {password, email} = ctx.request.body

  return Passport.authenticate('local', function(err, user, info, status) {
    // console.log('err', err)
    // console.log('user', user)
    // console.log('info', info)
    // console.log('status', status)
    if (err) {
      ctx.body = {
        code: -1,
        msg: err
      }
    } else {
      if (user) {
        ctx.body = {
          code: 0,
          msg: '登录成功',
          user
        }
        return ctx.login(user)
      } else {
        ctx.body = {
          code: 1,
          msg: info
        }
      }
    }
  })(ctx, next)
})
// test
router.get('/test', async (ctx, next) => {
  // console.log('host', process.env.NODE_ENV)
  // console.log('ctx', ctx.request)
  let ip = ctx.request.headers['x-forwarded-for'] ||
  // ctx.request.connection.remoteAddress ||
  ctx.request.socket.remoteAddress ||
  ctx.request.connection.socket.remoteAddress;
  console.log('ip', ip)
})
/*
  获取注册验证码(邮箱)
*/
router.post('/verify', async (ctx, next) => {
  let email = ctx.request.body.email
  // 邮箱
  if (!email) {
    ctx.body = {
      code: -1,
      msg: '请填写邮箱'
    }
    return false
  }
  const saveExpire = await Store.hget(`nodemail:${email}`, 'expire')
  // HGET nodemail:test expire
  // console.log('email', email)
  // console.log('saveExpire', saveExpire)
  // console.log('now', new Date().getTime())
  if (saveExpire && (new Date().getTime() - saveExpire < 1000 * 60)) {
    ctx.body = {
      code: -1,
      msg: '验证请求过于频繁，1分钟内1次'
    }
    return false
  }
  let transporter = nodeMailer.createTransport({
    service: 'qq',
    auth: {
      user: Email.smtp.user,
      pass: Email.smtp.pass
    }
  })
  let ko = {
    code: Email.smtp.code(),
    // expire: Email.smtp.expire(),
    expire: new Date().getTime(),
    // user: ctx.request.body.username
    user: ctx.request.body.email
    // email: ctx.request.body.email
  }
  let mailOptions = {
    from: `"认证邮件" <${Email.smtp.user}>`,
    // to: ko.email,
    to: ko.user,
    subject: '《07ge》注册邮件验证码',
    html: `感谢您在 07ge.com 中注册，您的注册邮件验证码码是 ${ko.code} ，有效期为30分钟`
  }
  await transporter.sendMail(mailOptions, (error, info) => {
    if (error) {
      return console.log(error)
    } else {
      // Store.hmset(`nodemail:${ko.user}`, 'code', ko.code, 'expire', ko.expire, 'email', ko.email)
      Store.hmset(`nodemail:${ko.user}`, 'code', ko.code, 'expire', ko.expire)
    }
  })
  ctx.body = {
    code: 0,
    msg: '验证码已发送，可能会有延时，有效期1分钟'
  }
})

/*
  退出
*/
router.get('/exit', async (ctx, next) => {
  await ctx.logout()
  if (!ctx.isAuthenticated()) {
    ctx.body = {
      code: 0
    }
  } else {
    ctx.body = {
      code: -1
    }
  }
})
/*
  找回修改密码(邮箱)
*/
router.post('/changepw', async (ctx) => {
  const {password, email, code} = ctx.request.body

  // let username = ''

  if (code) {
    const saveCode = await Store.hget(`nodemailcg:${email}`, 'code')
    const saveExpire = await Store.hget(`nodemailcg:${email}`, 'expire')
    if (code === saveCode) {
      if (new Date().getTime() - saveExpire > 1000 * 60 * 30) {
        ctx.body = {
          code: -1,
          msg: '验证码已过期，请重新尝试'
        }
        return false
      }
    } else {
      ctx.body = {
        code: -1,
        msg: '请填写正确的验证码'
      }
    }
  } else {
    ctx.body = {
      code: -1,
      msg: '请填写验证码'
    }
  }
  // 邮箱
  if (!email) {
    ctx.body = {
      code: -1,
      msg: '请填写邮箱'
    }
    return
  }
  // 密码
  if (!password) {
    ctx.body = {
      code: -1,
      msg: '请填写密码'
    }
    return
  }
  // 邮箱
  // let user = await User.find({email})
  let user = await mysqlp.query(`select email from user where email='${email}';`)
  console.log(user[0]);

  if (!user[0]) {
    ctx.body = {
      code: -1,
      msg: '该邮箱未注册'
    }
    return
  }
  
  // let nuser = await User.updateOne({password})
  let nuser = await mysqlp.query(`UPDATE user
        SET password='${password}'
        WHERE email='${email}';`)
  // console.log('nuser', nuser)
  // console.log('email', email)
  // console.log('password', password)

  if (nuser) {
    await ctx.logout()
    ctx.body = {
      code: 0,
      msg: '密码修改成功'
    }
    // let {password, email} = nuser
    
    // let res = await axios.post('/users/login', {email, password})
    // // console.log('res', res)
    // if (res.data && res.data.code === 0) {
    //   ctx.body = {
    //     code: 0,
    //     msg: '注册成功',
    //     user: res.data.user
    //   }
    // } else {
    //   ctx.body = {
    //     code: -1,
    //     msg: 'error'
    //   }
    // }
  } else {
    ctx.body = {
      code: -1,
      msg: '密码修改失败'
    }
  }
})
/*
  获取找回修改密码验证码(邮箱)
*/
router.post('/verifycg', async (ctx, next) => {
  let email = ctx.request.body.email
  // 邮箱
  if (!email) {
    ctx.body = {
      code: -1,
      msg: '请填写邮箱'
    }
    return false
  }
  const saveExpire = await Store.hget(`nodemailcg:${email}`, 'expire')
  // HGET nodemail:test expire
  // console.log('email', email)
  // console.log('saveExpire', saveExpire)
  // console.log('now', new Date().getTime())
  if (saveExpire && (new Date().getTime() - saveExpire < 1000 * 60)) {
    ctx.body = {
      code: -1,
      msg: '验证请求过于频繁，1分钟内1次'
    }
    return false
  }
  let transporter = nodeMailer.createTransport({
    service: 'qq',
    auth: {
      user: Email.smtp.user,
      pass: Email.smtp.pass
    }
  })
  let ko = {
    code: Email.smtp.code(),
    // expire: Email.smtp.expire(),
    expire: new Date().getTime(),
    // user: ctx.request.body.username
    user: ctx.request.body.email
    // email: ctx.request.body.email
  }
  let mailOptions = {
    from: `"认证邮件" <${Email.smtp.user}>`,
    // to: ko.email,
    to: ko.user,
    subject: '《07ge》修改密码邮件验证码',
    html: `您在 07ge.com 中申请修改密码，您的修改密码邮件验证码是 ${ko.code} ，有效期为30分钟`
  }
  await transporter.sendMail(mailOptions, (error, info) => {
    if (error) {
      return console.log(error)
    } else {
      // Store.hmset(`nodemail:${ko.user}`, 'code', ko.code, 'expire', ko.expire, 'email', ko.email)
      Store.hmset(`nodemailcg:${ko.user}`, 'code', ko.code, 'expire', ko.expire)
    }
  })
  ctx.body = {
    code: 0,
    msg: '验证码已发送，可能会有延时，有效期1分钟'
  }
})
/*
  获取用户信息
*/
router.get('/getUser', async (ctx) => {
  // console.log(ctx.isAuthenticated())
  if (ctx.isAuthenticated()) {
    const email = ctx.session.passport.user
    ctx.body={
      user:email.email
      // id:email._id
    }
  }else{
    ctx.body={
      user:'',
      email:''
    }
  }
})

module.exports = router
// export default router
